<script lang="ts" setup>
import { ref } from 'vue';
import { reactive } from 'vue';
import { Form, message } from 'ant-design-vue';
import { putSysUserUpdatePassApi } from '@/common/apis/user'
import { useUserStore } from '@/common/stores/users-store'
import { useRouter } from 'vue-router';

const router = useRouter()
const userStore = useUserStore()


const open = ref<boolean>(false);
const useForm = Form.useForm;
const labelCol = { span: 4 };
const wrapperCol = { span: 14 };
const modelRef = reactive({
    oldPassword: '',
    newPassword: '',
    repeat: '',
});

// 显示弹框
const showModal = () => {
    open.value = true;
};

const rulesRef = reactive({
    oldPassword: [
        { required: true, message: '请输入旧密码', trigger: 'change' },
        { min: 8, message: '密码至少为 8 位字符', trigger: 'blur' },
        {
            pattern: /^[^, ]+$/,
            message: '密码不允许包含空格或逗号',
            trigger: 'blur',
        },
    ],
    newPassword: [
        { required: true, message: '请输入新密码', trigger: 'change' },
        { min: 8, message: '密码至少为 8 位字符', trigger: 'blur' },
        {
            pattern: /^[^, ]+$/,
            message: '密码不允许包含空格或逗号',
            trigger: 'blur',
        },
    ],
    repeat: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        // 自定义校验规则
        {
            validator: (rule, value) => {
                if (value === modelRef.newPassword) {
                    return Promise.resolve();
                }
                return Promise.reject('两次输入的密码不一致');
            },
            trigger: 'blur',
        },
    ],
});

const { validate, validateInfos } = useForm(modelRef, rulesRef, {
    onValidate: (...args) => console.log(...args),
});

// 点击确定
const handleOk = async () => {
    await validate().then(async () => {
        // 调用接口 修改密码
        await putSysUserUpdatePassApi(modelRef)
        userStore.clearUserInfo()
        message.success('修改成功');
        router.push('/login')
    });
    open.value = false;
};



defineExpose({
    showModal,
});
</script>

<template>
    <div>
        <a-modal v-model:open="open" title="修改密码" @ok="handleOk">
            <a-form :label-col="labelCol" :wrapper-col="wrapperCol">
                <!-- 修改密码 -->
                <a-form-item label="旧密码" v-bind="validateInfos.oldPassword">
                    <a-input v-model:value="modelRef.oldPassword" />
                </a-form-item>
                <!-- 新密码 -->
                <a-form-item label="新密码" v-bind="validateInfos.newPassword">
                    <a-input-password v-model:value="modelRef.newPassword" />
                </a-form-item>
                <!-- 重复密码 -->
                <a-form-item label="重复密码" v-bind="validateInfos.repeat">
                    <a-input-password v-model:value="modelRef.repeat" />
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>
